package com.zengqingfa.springboot.redis.listener;

import com.zengqingfa.springboot.redis.constants.RedisCacheKeyConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author zengqingfa
 * @className RedisKeyExpirationListener
 * @description
 * @create 2022/9/24 19:54
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


    @Resource
    private RedisTemplate redisTemplate;

    public RedisKeyExpirationListener(RedisMessageListenerContainer redisMessageListenerContainer) {
        super(redisMessageListenerContainer);
    }


    /**
     * 针对 redis 数据失效事件，进行数据处理
     * 如果是多个不同的key,可以针对Message进行处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //获取到key
        String key = message.toString();
        // 拿到value 获取到的value为空，此时key过期，拿不到对应的value,业务数据在key上体现,比如拼接主键之类的
        Object val = redisTemplate.opsForValue().get(key);
        log.info("监听Redis key过期，key：{}，channel：{},value:{}",key, new String(pattern), val);
        //获取到业务主键
        String[] split = key.split("::");
        String bizId=split[1];
        if (message.toString().contains(RedisCacheKeyConstants.EXPIRE_KEY_MESSAGE)) {
            //TODO 执行短信业务
            //获取到短信的主键 bizId

            log.info("执行短信业务：");
        } else if (message.toString().contains(RedisCacheKeyConstants.EXPIRE_KEY_ORDER)) {
            //TODO 执行订单业务
            //获取到订单的主键 bizId

            log.info("执行订单业务：");
        }
    }
}